package self.hoy.demo.sms.ali;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import self.hoy.demo.sms.SortMessageSender;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

/**
 * 对接阿里云SMS
 * TODO 添加短信发送记录
 * @author hyh
 * @date 2020/8/12
 */
@Data
@ConditionalOnProperty(
        prefix = "spring.alicloud.sms",
        value = {"enabled"},
        matchIfMissing = true
)
@ConditionalOnMissingBean
@ConfigurationProperties(prefix = "spring.alicloud.sms")
public class ALiSMSImpl implements SortMessageSender {

    // 【1】请求地址 支持http 和 https 及 WEBSOCKET
    private String host;// = "https://smsmsgs.market.alicloudapi.com";

    // 【2】后缀
    private String path;// = "/sms/";

    // 【3】开通服务后 买家中心-查看AppCode
    private String appcode;// = "590d607322794bfe95d0d6002c2c47f0";

    //  【可选】签名编号
    private String sign;// = "175622";

    //  【4】模板编号【见产品详情】
    private String skin;// = "1";

    /**
     * 节约模式，
     * true时表示打印验证码到控制台，
     * false时表示通过短信接口发送验证码给移动设备
     */
    @Value("${thrift:false}")
    private Boolean thrift;


    @Override
    public void send(String phone, String code, String template) {
        if (thrift != null && thrift == true) {
            System.out.println("给" + phone + "的验证码是 " + code);
            return;
        }
        //TODO 兼容更多短信模板
        this.send(phone, code);
    }

    private void send(String phone, String code) {
//        String code = "123456";  // 【4】请求参数，详见文档描述
//        String phone = "18030939917";  //  【4】请求参数，详见文档描述
        String urlSend = host + path + "?code=" + code +"&phone="+phone +"&sign="+sign +"&skin="+skin;   // 【5】拼接请求链接
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE (中间是英文空格)
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                System.out.println("正常请求计费(其他均不计费)");
                System.out.println("获取返回的json:");
                System.out.print(json);
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    System.out.println("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    System.out.println("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    System.out.println("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    System.out.println("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    System.out.println("套餐包次数用完 ");
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    System.out.println(error);
                }
            }

        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
        } catch (Exception e) {
            // 打开注释查看详细报错异常信息
            // e.printStackTrace();
        }

    }

    /*
     * 读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}
